package com.callbell.cas.handler;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import com.callbell.cas.util.ResourceBundleUtil;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.callbell.cas.sdk.impl.LuosimaoSMS;
import com.callbell.cas.util.Digests;
import com.callbell.cas.util.Encodes;
import com.callbell.cas.util.SMSKit;
import com.google.code.kaptcha.Constants;

/**
 * 用户注册
 * @author xlh
 *
 */
@SuppressWarnings("deprecation")
public class UserRegisterController extends AbstractController{
	
private CentralAuthenticationService centralAuthenticationService;
	
	private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;
	
	private SimpleJdbcTemplate jdbcTemplate;
	
	private DataSource dataSource;
	
	private static final int HASH_INTERATIONS = 264544;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String option = ServletRequestUtils.getStringParameter(request, "option");
		ModelAndView signinView = new ModelAndView();
		String viewName = "casRegisterView";
		if ("submit".equals(option)){//保存用户注册信息
			viewName = saveRegister(request, response);
			signinView.setViewName(viewName);
		} else if("sendMessage".equals(option)){//发送短信验证码
			sendMessage(request);
		} else if ("checkUser".equals(option)){//验证用户是否已被注册
			boolean bln = isRegister(request);
			response.getWriter().println(bln);
			return null;
		} else if ("checkCapt".equals(option)){//检查图形验证码输入是否正确
			boolean bln = isCapTextTrue(request);
			response.getWriter().println(bln);
			return null;
		} else if ("checkCode".equals(option)){//检查手机验证码输入是否正确
			boolean bln = isMsgCodeTrue(request);
			response.getWriter().println(bln);
			return null;
		} else {
			String service = ServletRequestUtils.getStringParameter(request, "service");
			request.setAttribute("service", service);
			signinView.setViewName(viewName);
		}
		return signinView;
	}
	
	private void sendMessage(HttpServletRequest request) throws ServletRequestBindingException{
		String mobilePhone = ServletRequestUtils.getStringParameter(request, "mobilePhone");
		SMSKit.setSmsService(new LuosimaoSMS());
		String msgCode = SMSKit.sendRandomCheckCode(mobilePhone, "尊敬的用户");
		HttpSession session = request.getSession();
		session.setAttribute("currentTime", System.currentTimeMillis());
		session.setMaxInactiveInterval(1800);
		session.setAttribute("msgCode", msgCode);
	}
	
	private String saveRegister(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
		String mobilePhone = ServletRequestUtils.getStringParameter(request, "mobilePhone");//手机号码
		String password = ServletRequestUtils.getStringParameter(request, "pwd");// 密码
		
		byte[] bsalt = Digests.generateSalt(32);
		String salt = Encodes.encodeHex(bsalt);
		Sha512Hash sha = new Sha512Hash(password, bsalt, HASH_INTERATIONS);
		String saltPassword = sha.toHex();
		
		Map<String, Object> valueMap = new HashMap<String, Object>();
		valueMap.put("mobile", mobilePhone);
		valueMap.put("password", saltPassword);
		valueMap.put("salt", salt);
		valueMap.put("createTime", new Date());
		int count = jdbcTemplate.update("insert into user(account, mobile, password, salt, create_time) values(:mobile, :mobile, :password, :salt, :createTime)", valueMap);
		
		if(count > 0){//注册成功 自动登录
			//帮我加这个进去  在插入用户之后
			int userid = jdbcTemplate.queryForInt("select user_id from user where account  = ?", mobilePhone);
			jdbcTemplate.update("INSERT INTO user_map_role (`user_id`, `role_id`, `create_time`, `statue`) VALUES (?, '1', NOW(), '1')",userid);


			request.getSession().removeAttribute("msgCode");
			request.getSession().removeAttribute("currentTime");
			UsernamePasswordCredentials credentials = new UsernamePasswordCredentials();
			credentials.setUsername(mobilePhone);
			credentials.setPassword(password);
			credentials.setLoginType("2");
			
			try {
				String ticketGrantingTicket = centralAuthenticationService.createTicketGrantingTicket(credentials);
				ticketGrantingTicketCookieGenerator.addCookie(request, response, ticketGrantingTicket);
			} catch (TicketException e) {
				e.printStackTrace();
			}
		}
		String service = ServletRequestUtils.getStringParameter(request, "service", "");
		//此处是否允许:相对地址和绝对地址（有待测试）
		return ("redirect:/login" + (service.length() > 0 ? "?service=" + service : ""));
	}
	
	private boolean isRegister(HttpServletRequest request) throws ServletRequestBindingException{
		String mobilePhone = ServletRequestUtils.getStringParameter(request, "mobilePhone");//手机号码
		List<Map<String, Object>> list = jdbcTemplate.queryForList("select user_id as userId from user where account=?", mobilePhone);
		return (list != null && list.size() > 0) ? false : true;
	}
	
	private boolean isCapTextTrue(HttpServletRequest request) throws ServletRequestBindingException{
		String checkCode = ServletRequestUtils.getStringParameter(request, "verse_regis");//图形验证码
		String capText = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
		return checkCode.equalsIgnoreCase(capText) ? true : false;
	}
	
	private boolean isMsgCodeTrue(HttpServletRequest request) throws ServletRequestBindingException{
		String msgCode = ServletRequestUtils.getStringParameter(request, "msgCode");//短信验证码
		String code = request.getSession().getAttribute("msgCode")+"";
		if(code == null || "".equals(code) || !msgCode.equalsIgnoreCase(code)){
			return false;
		}
		String currentTime = request.getSession().getAttribute("currentTime") + "";
		long endTime = System.currentTimeMillis();
		if((endTime - (Long.parseLong(currentTime))) > 180000){
			return false;
		}
		return true;
	}
	
	public void setDataSource(final DataSource dataSource) {
		this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
	}

	protected final DataSource getDataSource() {
		return this.dataSource;
	}
	
	public CentralAuthenticationService getCentralAuthenticationService() {
		return centralAuthenticationService;
	}

	public void setCentralAuthenticationService(CentralAuthenticationService centralAuthenticationService) {
		this.centralAuthenticationService = centralAuthenticationService;
	}

	public CookieRetrievingCookieGenerator getTicketGrantingTicketCookieGenerator() {
		return ticketGrantingTicketCookieGenerator;
	}

	public void setTicketGrantingTicketCookieGenerator(
			CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator) {
		this.ticketGrantingTicketCookieGenerator = ticketGrantingTicketCookieGenerator;
	}
}
